package com.example.demo.util;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Component;

@Component
public class RedisListUtil {

	@Autowired
	private ListOperations<String, Object> listOperations;
	
	public long lpush(String key, Object ...values) {
		return listOperations.leftPushAll(key, Arrays.asList(values));
	}
	
	public long rpush(String key, Object ...values) {
		return listOperations.rightPushAll(key, values);
	}
	
	public long lpushx(String key, Object value) {
		return listOperations.leftPushIfPresent(key, value);
	}
	
	public long rpushx(String key, Object value) {
		return listOperations.rightPushIfPresent(key, value);
	}
	
	public Object lpop(String key) {
		return listOperations.leftPop(key);
	}
	
	public Object blpop(String key, long seconds) {
		return listOperations.leftPop(key, seconds, TimeUnit.SECONDS);
	}
	
	public Object rpop(String key) {
		return listOperations.rightPop(key);
	}
	
	public Object brpop(String key, long seconds) {
		return listOperations.rightPop(key, seconds, TimeUnit.SECONDS);
	}
	
	public long llen(String key) {
		return listOperations.size(key);
	}
	
	public List<Object> lrange(String key, long start, long stop) {
		return listOperations.range(key, start, stop);
	}
	
	public long lrem(String key, long count, Object value) {
		return listOperations.remove(key, count, value);
	}
	
	public void lset(String key, long index, Object value) {
		listOperations.set(key, index, value);
	}
	
	public Object lindex(String key, long index) {
		return listOperations.index(key, index);
	}
	
	public void ltrim(String key, long start, long stop) {
		 listOperations.trim(key, start, stop);
	}
	
	public void linsert(String key, String beforeOrAfter, String pivot, String value) {
		long index = getIndexByPivot(key, pivot);
		if(beforeOrAfter.equals("before")) {
			lset(key, index-1, value);
		}else {
			lset(key, index+1, value);
		}
	}
	
	public Object rpoplpush(String source, String destination) {
		return listOperations.rightPopAndLeftPush(source, destination);
	}
	
	public long getIndexByPivot(String key, String pivot) {
		long rsIndex = 0;
		long len = llen(key);
		for(int i = 0; i < len; i++) {
			String obj = lindex(key, i).toString();
			if(obj.equals(pivot)) {
				rsIndex = i;
				break;
			}
		}
		return rsIndex;
	}
	
}
